<?php

namespace App\Services;

use App\Models\UserUrgentModel;
use App\Utils\StringUtils;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserUrgentService
{
    /**
     * 紧急联系人添加或修改
     * @param Request $request
     * @return JsonResponse|void
     */
    public static function addEmergencyContact($data)
    {
        $userId = request() -> userId;
        $name = $data['name'];
        $phone = $data['phone'];
        if(!StringUtils::isMobile($phone)){
            throw new \Exception('手机号格式不正确');
        }
        $id = UserUrgentModel::query()->where('user_id',$userId)->value('id');
        if($id > 0) {
            $res = UserUrgentModel::where('id', $id)->update([
                'name' => $name,
                'phone' => $phone
            ]);
        }else {
            $res = UserUrgentModel::insert([
                'user_id' => $userId,
                'name' => $name,
                'phone' => $phone
            ]);
        }
        return $res;
    }

    /**
     * 紧急联系人查询
     * @param Request $request
     * @return JsonResponse|void
     */
    public static function getEmergencyContact()
    {
        $userId = request() -> userId;
        $res = UserUrgentModel::where('user_id', $userId )->first();
        return $res;
    }

}
